﻿using System;

/*代表方向*/
public enum ESnakeDirection
{
    Up,
    Down,
    Left,
    Right,
    None,
}

/*代表一个蛇身上一个节点的数据*/
public class SnakeBodyBlock
{	
    public int x, y;
	public char element;
	public ESnakeDirection aheadDirection;
	public ESnakeDirection afterDirection;

    //构造函数，初始化蛇节点的位置，显示字符，以及节点的方向（新生成的节点，头朝向与尾朝向永远相反）
	public SnakeBodyBlock(int x, int y, char element, ESnakeDirection direction = ESnakeDirection.Up)
	{
		this.x = x;
		this.y = y;
		this.element = element;

		if(direction != ESnakeDirection.None)
        {
			this.aheadDirection = direction;
			this.afterDirection = ReverseDirection(this.aheadDirection);
		}
        else
        {
			return;
        }
    }

    //静态方法，返回反向的方向
	static public ESnakeDirection ReverseDirection(ESnakeDirection originDirection)
    {
        switch (originDirection)
        {
			case ESnakeDirection.Up:
				return ESnakeDirection.Down;
			case ESnakeDirection.Down:
				return ESnakeDirection.Up;
			case ESnakeDirection.Left:
				return ESnakeDirection.Right;
			case ESnakeDirection.Right:
				return ESnakeDirection.Left;
			default:
				break;
        }
		return ESnakeDirection.None;
    }

    //在当前节点的前方或后方生成新的节点，并返回
	public SnakeBodyBlock GetNewBlock(bool atHead)
    {
        ESnakeDirection targetDirection;
        ESnakeDirection newAheadDirection;
        if (atHead)
        {
            targetDirection = aheadDirection;
            newAheadDirection = aheadDirection;
        }
        else
        {
            targetDirection = afterDirection;
            newAheadDirection = ReverseDirection(afterDirection);
        }

		SnakeBodyBlock aheadBlock = new SnakeBodyBlock(0, 0, element, newAheadDirection);

        switch (targetDirection)
        {
            case ESnakeDirection.Up:
                aheadBlock.x = x;
                aheadBlock.y = y - 1;
                break;

            case ESnakeDirection.Down:
                aheadBlock.x = x;
                aheadBlock.y = y + 1;
                break;

            case ESnakeDirection.Left:
                aheadBlock.x = x - 1;
                aheadBlock.y = y;
                break;

            case ESnakeDirection.Right:
                aheadBlock.x = x + 1;
                aheadBlock.y = y;
                break;

            default:
                break;
        }

        return aheadBlock;
    }

    //判断当前节点的位置是否在屏幕内，如果不在，将该节点的位置更改为穿透屏幕后的位置
    public void PortalPosition(int screenWidth, int screenHeight)
    {
        if(0 <= x && x < screenWidth && 0 <= y && y < screenHeight)
        {
            return;
        }

        if(x < 0)
        {
            x = screenWidth + x;
        }
        else if(x >= screenWidth){
            x = x - screenWidth;
        }

        if(y < 0)
        {
            y = screenHeight + y;
        }
        else if(y >= screenHeight)
        {
            y = y - screenHeight;
        }

        this.PortalPosition(screenWidth, screenHeight);
    }
}
